// Package supermarket_director 商场负责人
package supermarket_director

import (
	"context"

	"shop-manager/internal/do"

	"gorm.io/gorm"
)

//go:generate newc
type SupermarketDirectorRepo struct {
	db *gorm.DB
}

// 保持两个参数, 统一处理
func (s *SupermarketDirectorRepo) Create(ctx context.Context, data *do.SupermarketDirector) (id int, err error) {
	err = s.db.WithContext(ctx).Create(data).Error
	return data.ID, err
}

// 只限部分字段可修改
func (s *SupermarketDirectorRepo) Update(ctx context.Context, data *do.SupermarketDirector) (err error) {
	origin := &do.SupermarketDirector{}
	if err := s.db.WithContext(ctx).First(origin, data.ID).Error; err != nil {
		return err
	}

	origin.DirectorID = data.DirectorID
	origin.SupermarketID = data.SupermarketID
	origin.DirectorPoints = data.DirectorPoints
	origin.Note = data.Note

	return s.db.WithContext(ctx).Save(origin).Error
}

type ListParam struct {
	Page     int
	PageSize int

	IDs            []int
	DirectorIDs    []int
	SupermarketIDs []int

	Search string // 模糊搜索 , TODO 暂不支持
	// 排序, 格式为 field [ASC/DESC], ...
	Sorts string
}

func (s *SupermarketDirectorRepo) List(ctx context.Context, param ListParam) (listData []*do.SupermarketDirector, total int64, err error) {
	if param.Page <= 0 {
		param.Page = 1
	}
	if param.PageSize <= 0 {
		param.PageSize = do.DefaultPageSize
	}
	if param.PageSize > do.MaxPageSize {
		param.PageSize = do.MaxPageSize
	}

	err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
		if len(param.IDs) > 0 {
			tx = tx.Where("id IN ?", param.IDs)
		}
		if len(param.DirectorIDs) > 0 {
			tx = tx.Where("director_id IN ?", param.DirectorIDs)
		}
		if len(param.SupermarketIDs) > 0 {
			tx = tx.Where("supermarket_id IN ?", param.SupermarketIDs)
		}
		if param.Sorts != "" {
			tx = tx.Order(param.Sorts)
		}

		if param.Search != "" {
			tx.Model(&do.SupermarketDirector{}).
				Joins("left join person on person.id = supermarket_director.director_id AND person.type = ? AND person.name like ?", do.PersonType_SupermarketDirector, "%"+param.Search+"%")
		} else {
			tx.Model(&do.SupermarketDirector{})
		}
		err = tx.Count(&total).Error
		if err != nil {
			return err
		}

		offset := (param.Page - 1) * param.PageSize
		err = tx.
			Offset(offset).
			Limit(param.PageSize).
			Find(&listData).Error
		if err != nil {
			return err
		}

		return err
	})
	return listData, total, err
}
